package com.chen.interceptor;

import com.chen.constant.ResultConstant;
import com.chen.context.BaseContext;
import com.chen.exception.NotLoginError;
import com.chen.prop.JwtProp;
import com.chen.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt 拦截器
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProp jwtProp;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!request.getMethod().equals("OPTIONS")) {
            String token = request.getHeader(jwtProp.getTokenName());
            log.info("当前的请求路径为：{}", request.getRequestURI());
            log.info("当前接收到到的令牌{}", token);
            // 没有携带令牌
            if (token == null || token.length() == 0) {
                throw new NotLoginError(ResultConstant.MSG_UNAUTHORIZED_ERROR);
            }
            // 令牌解析错误
            try {
                Claims claims = JwtUtil.parseJWT(jwtProp.getKey(), token);
                Long id = claims.get("id", Long.class);
                // 将用户id存储在当前线程对象中
                BaseContext.setCurrentId(id);
                log.info("当前的用户为：{}", BaseContext.getCurrentId());
                return true;
            } catch (Exception e) {
                // 令牌解析错误
                throw new NotLoginError(ResultConstant.MSG_UNAUTHORIZED_ERROR);
            }
        }

        return true;
    }
}
   /* @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("");
        String token = request.getParameter("token");
        if (token == null || token.length() == 0) {
            throw new NotLoginError(ResultConstant.MSG_UNAUTHORIZED_ERROR);
        }
        // 令牌解析错误
        try {
            Claims claims = JwtUtil.parseJWT(jwtProp.getKey(), token);
            Long id = claims.get("id", Long.class);
            // 将用户id存储在当前线程对象中
            BaseContext.setCurrentId(id);
            log.info("当前的用户为：{}", BaseContext.getCurrentId());
            return true;
        } catch (Exception e) {
            // 令牌解析错误
            throw new NotLoginError(ResultConstant.MSG_UNAUTHORIZED_ERROR);
        }

    }
}
*/